#include "tlm_srv.h"

int tlm_srv_init(){
  int sock;
  struct sockaddr_in addr;
  addr.sin_family = AF_INET;
  addr.sin_port = htons(TLM_SERVER_PORT);
  addr.sin_addr.s_addr = htonl(TLM_SERVER_IP);

  assert((sock = socket(AF_INET, SOCK_DGRAM, 0)) != -1);
  assert((fcntl(sock, F_SETFL, O_NONBLOCK, 1)) != -1);
  assert(connect(sock, (struct sockaddr *)&addr, sizeof(addr)) != -1);

  return sock;
}

static void main_timer_cb(EV_P_ ev_timer *w, int revents){
  TLM_TIMER_t* tlm_timer = ((TLM_TIMER_t*)w);
  gcs_tlm_t tlm;

  bcshm_read(SHM_FC_TLM, &tlm_timer->shm, &tlm.fc_tlm);
  bcshm_read(SHM_FTC_TLM, &tlm_timer->shm, &tlm.ftc_tlm);
  bcshm_read(SHM_BC_TLM, &tlm_timer->shm, &tlm.bc_tlm);

  //gcs_tlm_print(tlm);

  send_tlm(tlm_timer->sock, &tlm);
}

void tlm_srv_start(){
  TLM_TIMER_t tlm_timer;
  struct ev_loop *loop;

  tlm_timer.sock = tlm_srv_init();
  loop = ev_loop_new(EVFLAG_NOENV | EVBACKEND_EPOLL);
  bcshm_open(&tlm_timer.shm);
  ev_init(&tlm_timer.timer, main_timer_cb);
  tlm_timer.timer.repeat = TLM_SRV_PERIOD;

  ev_timer_again(loop, &tlm_timer.timer);
  ev_run(loop, 0); 
}

void send_tlm(int sock, gcs_tlm_t* tlm){
  send(sock, tlm, sizeof(gcs_tlm_t), 0);
}

int recv_tlm(int sock, gcs_tlm_t* tlm){
  return recv(sock, tlm, sizeof(gcs_tlm_t), 0);
}



